//
//  QDGeRenController.m
//  simulateQuickDoctor
//
//  Created by 姚华杰 on 2017/3/23.
//  Copyright © 2017年 PipiXia. All rights reserved.
//

#import "QDGeRenController.h"
#import "QDIndividualCell.h"
#import "QDIndividualModel.h"
#import "QDLoginModel.h"
#import <HMPreviewViewController.h>

@interface QDGeRenController () <UITableViewDelegate, UITableViewDataSource,UIAlertViewDelegate, UIGestureRecognizerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>



@property (weak, nonatomic) IBOutlet UIImageView *imgView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,strong)NSMutableArray * modelList;

@property (weak, nonatomic) IBOutlet UIButton *iconBtn;

//相应的组
@property(nonatomic,assign) NSInteger section;
//相应的行
@property(nonatomic,assign) NSInteger row;
//数据
@property (nonatomic,copy) NSString *titleLabel;
//tabLabel
@property(nonatomic,weak) UITableView *tabView;

@property(nonatomic,strong)QDLoginModel *loginModel;
@end

@implementation QDGeRenController
    



- (void)viewDidLoad {
    [super viewDidLoad];
    
    _loginModel = [QDUserInfo defaultUserInfo].model;
    
    _modelList = [NSMutableArray array];
    
    _modelList = [QDIndividualModel gettingSettingModelArr];
    
}



- (void)setupUI
{
    
    _tabView.tableHeaderView = _imgView;
    
    //创建一个图片视图
//    UIImageView *iconView = [[UIImageView alloc] init];
    
    //加载图片
    UIImage *image = [UIImage imageNamed:@"imgback"];
    
    //获取图片尺寸
    CGSize size = image.size;
    
    //开启位图上下文
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    
    //创建圆形路径
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    
    //设置为裁剪区域
    [path addClip];
    
    //绘制图片
    [image drawAtPoint:CGPointZero];
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭上下文
    UIGraphicsEndImageContext();
    
    [_iconBtn setImage:img forState:UIControlStateNormal];
    
    [_iconBtn addTarget:self action:@selector(clickIcon) forControlEvents:UIControlEventTouchUpInside];

    
//    //把新创建的图片视图添加到当前控制器的视图上
//    [self.view addSubview:iconView];
//    
//    //把iconView放在最上层
//    [self.view bringSubviewToFront:iconView];
//    
//    //约束
//    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.centerX.equalTo(_imgView.mas_centerX);
//        make.bottom.equalTo(_imgView.mas_bottom).offset(30);
//        make.height.width.mas_equalTo(85);
//    }];
//    
//    //创建点击手势
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickIcon:)];
//    
//    //把点击手势添加在iconView上
//    [iconView addGestureRecognizer:tap];
    
    //注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"QDIndividualCell" bundle:nil] forCellReuseIdentifier:@"IndividualCell"];
    
    //设置数据源
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    //设置预估行高
    _tableView.estimatedRowHeight = 100;
    //设置真实行高
    _tableView.rowHeight = UITableViewAutomaticDimension;
    
    
    
}

- (void)clickIcon {
    
    NSLog(@"更换图片");
    
    //创建图片选择器
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc]init];
    //指定源类型
    pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    pickerImage.delegate = self;
    
    //推出控制器
    [self presentViewController:pickerImage animated:YES completion:nil];

}

//选取图片调用此方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    
    NSString *imageName = info[@"UIImagePickerControllerMediaType"];
    
//    iconName = imageName;
    
    [_iconBtn setImage:image forState:UIControlStateNormal];
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    
    NSString *fileName = [path stringByAppendingPathComponent:imageName];
    
    NSData *data = UIImagePNGRepresentation(image);
    
    [data writeToFile:fileName atomically:YES];
    
    //添加通知，将leftbar头像进行修改
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center postNotificationName:@"changeIcon" object:nil userInfo:@{@"key":fileName}];
    
    //获取图片尺寸
    CGSize size = image.size;
    
    //开启位图上下文
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    
    //创建圆形路径
    UIBezierPath *path1 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    
    //设置为裁剪区域
    [path1 addClip];
    
    //绘制图片
    [image drawAtPoint:CGPointZero];
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭上下文
    UIGraphicsEndImageContext();
    
    [_iconBtn setImage:img forState:UIControlStateNormal];
    
     [picker dismissViewControllerAnimated:YES completion:nil];

}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _modelList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QDIndividualCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IndividualCell" forIndexPath:indexPath];
    
   
    
    QDIndividualModel *model = _modelList[indexPath.row];
//    model.details = [_loginModel valueForKey: [self getKeyByEnumName:indexPath.row]];
    cell.model = model;
    
    return cell;
}

/**
 选中某行调用此方法
 
 @param tableView tableView
 @param indexPath 某行
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.section = indexPath.section;
    
    self.row = indexPath.row;
    
    switch (indexPath.row) {
        case 0:
            
            //修改姓名
            [self updateIndividualWith:@"姓名"];
            break;
        case 1:
            
            //修改年龄
            [self updateIndividualWith:@"年龄"];
            break;
        case 2:
            
            //修改性别
            [self updateIndividualWith:@"性别"];
            break;
        case 3:
            
            //修改身高
            [self updateIndividualWith:@"身高"];
            break;
        case 4:
            
            //修改体重
            [self updateIndividualWith:@"体重"];
            break;
        case 5:
            
            //修改籍贯
            [self updateOrigin];
            break;
        case 6:
            
            //修改长居地
            [self updateOrigin];
            break;
        case 7:
            
            //修改联系方式
            [self updateIndividualWith:@"联系方式"];
            break;
        case 8:
            
            //修改证件号码
            [self updateIndividualWith:@"证件号码"];
            break;
        default:
            break;
    }
}

-(void) updateOrigin {
    
    
}


#pragma mark  - 修改个人信息
-(void) updateIndividualWith:(NSString *) title{
    
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"" preferredStyle:UIAlertControllerStyleAlert];
   
    __block id value = nil;
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        value = textField.text;
    }];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self updateInfoTitle:value];
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UIAlertView代理
//
//-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//    
//    //点击确定时
//    if (buttonIndex == 1) {
//        //更新数据
//        //1.获取文本框当前内容
//        NSString *text = [alertView textFieldAtIndex:0].text;
//        
//        //        NSLog(@"%@",text);
//        //2.修改当前选中的模型
//        NSDictionary *model = _modelList[self.row];
//        
//        NSDictionary *newModel = @{model.allKeys.lastObject : text};
//        
//        NSString *key = [newModel allKeys].lastObject;
//        
//        id value = [NSString stringWithFormat:@"%@",newModel[key]];
//        
//        [self updateInfoTitle:value];
//        
//        [_modelList replaceObjectAtIndex:self.row withObject:newModel];
//        
//        //3.刷新tableView
//        NSIndexPath *idxPath = [NSIndexPath indexPathForRow:self.row inSection:0];
//        //局部刷新,刷新指定的行
//        [self.tabView  reloadRowsAtIndexPaths:@[idxPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//    }
//   
//}


#pragma mark - 修改本地数据
-(void) updateInfoTitle :(id) value {
    
    switch (self.row) {
        case 0:
            _loginModel.true_name = value;
            break;
            
        case 1:
            _loginModel.age = value;
            break;
            
        case 2:
            _loginModel.gender = value;
            break;
            
        case 3:
            _loginModel.height = value;
            break;
            
        case 4:
            _loginModel.weight = value;
            break;
            
        case 5:
            _loginModel.address = value;
            break;
            
        case 6:
            _loginModel.residence = value;
            break;
            
        case 7:
            _loginModel.mobile_number = value;
            break;
            
        case 8:
            _loginModel.card_number = value;
            break;
            
        default:
            break;
    }
    
    NSLog(@"%@",_loginModel);
}


- (NSString*)getKeyByEnumName:(NSUInteger)enumName{
    
    NSString* keyName = nil;

    switch (enumName) {
        case 0:
            
            keyName = @"true_name";
            
            break;
        case 1:
            
            keyName = @"age";
            
            break;
        case 2:
            
            //修改性别
            keyName = @"gender";
            break;
        case 3:
            
            keyName = @"height";
            break;
        case 4:
            
            keyName = @"weight";
            break;
        case 5:
            
            keyName = @"address";
            break;
        case 6:
            
            //修改长居地
            keyName = @"residence";
            break;
        case 7:
            
            //修改联系方式
            keyName = @"mobile_number";
            break;
        case 8:
            
            //修改证件号码
            keyName = @"card_number";
        default:
            break;
    }
    
    return keyName;
}

@end
